import requests
from flask import (
    Blueprint,
    render_template,
    request,
    redirect,
    url_for,
    session,
    g,
    jsonify
)
from applications.common.utils.http import fail_api, success_api
from applications.models import User, EmailCaptchaModel, Role
from applications.common.utils.user_login_required import user_login_required
from applications.common.utils.mail import EmailisValid
from applications.common.utils.validate import xss_escape
from applications.extensions import db, mail
from flask_mail import Message
from applications.view.mail.send import send_email_captcha
import string
import random

user_index = Blueprint('user', __name__, url_prefix='/user')


@user_index.route('/login', methods=['POST', 'GET'])
def user_login():
    if request.method == 'GET':
        if session.get("client_user_id"):
            return redirect(url_for('spiderIndex.index'))
        return render_template('User/login.html')
    else:
        req = request.form
        username = req.get('username')
        password = req.get('password')
        if not username or not password:
            return fail_api(msg="用户名或密码没有输入")

        user = User.query.filter_by(username=username).first()

        if not user:
            return fail_api(msg="不存在的用户")

        if user.enable == 0:
            return fail_api(msg="用户被暂停使用")

        if username == user.username and user.validate_password(password):
            session['client_user_id'] = user.id
            return success_api(msg="登录成功")
        return fail_api(msg="用户名或密码错误")


@user_index.route('/logout', methods=['POST', 'GET'])
@user_login_required(log=False)
def user_logout():
    session.pop('client_user_id')
    return success_api(msg="注销成功")


@user_index.route('/register', methods=['POST', 'GET'])
def user_register():
    if request.method == "GET":
        return render_template("User/register.html")
    else:
        req = request.form
        username = xss_escape(req.get('username'))
        password = xss_escape(req.get('password'))
        realname = xss_escape(req.get('realname'))
        captcha = xss_escape(req.get('captcha'))

        if not EmailisValid(username):
            return fail_api(msg="邮箱错误")

        if not username or not realname or not password:
            return fail_api(msg="账号姓名密码不得为空")

        user = User.query.filter_by(username=username).first()
        if user:
            return fail_api(msg='用户已存在')

        password_len = len(password)
        required_len = 8
        if password_len < required_len:
            return fail_api(msg="密码过短")

        cnt = 0
        for i in password:
            if i.isdigit():
                ++cnt

        realname_required_len = 15
        realname_required_len_min = 4
        if len(realname) > realname_required_len or len(realname) < realname_required_len_min:
            return fail_api(msg="昵称需要在4-15个字符之间")

        if password_len == cnt:
            return fail_api(msg="密码不能全为数字")

        captcha_model = EmailCaptchaModel.query.filter_by(email=username).first()
        if not captcha_model or captcha_model.captcha.lower() != captcha.lower():
            return fail_api(msg="验证码错误")

        user = User(username=username, realname=realname, enable=1, dept_id=21)
        user.set_password(password)
        db.session.add(user)
        common_user = Role.query.filter_by(id=2).first()
        user.role.append(common_user)
        db.session.commit()
        return success_api(msg="注册成功")


@user_index.route('/captcha', methods=['POST'])
def get_email_captcha():
    email = request.form.get('email')
    letters = string.ascii_letters + string.digits
    captcha = "".join(random.sample(letters, 4))
    if email:
        message = Message(
            subject='自动发送-验证码',
            recipients=['1531982951@qq.com'],
            body=f"验证码：{captcha}",
        )
        try:
            send_email_captcha(message)
            captcha_model = EmailCaptchaModel.query.filter_by(email=email).first()
            if captcha_model:
                captcha_model.captcha = captcha
                db.session.commit()
            else:
                captcha_model = EmailCaptchaModel(email=email, captcha=captcha)
                db.session.add(captcha_model)
                db.session.commit()
            return jsonify({"code": 200})
        except:
            return jsonify({"code": 400, "message": "邮件发送失败!"})
    else:
        return jsonify({"code": 400, "message": "请先传递邮箱!"})


@user_index.route('/self', methods=['GET'])
@user_login_required(log=False)
def get_user_info_index():
    return render_template('User/personalInfo.html')


# 更改用户名，密码，邮箱
@user_index.get('/self/editPassword')
@user_login_required(log=False)
def user_edit_password():
    return render_template('User/edit_password.html')


@user_index.put('/self/editPassword')
@user_login_required(log=False)
def user_edit_password_put():
    res_json = request.json
    if res_json.get("newPassword") == '':
        return fail_api("新密码不得为空")
    if res_json.get("newPassword") != res_json.get("confirmPassword"):
        return fail_api("俩次密码不一样")
    user = g.client_user
    is_right = user.validate_password(res_json.get("oldPassword"))
    if not is_right:
        return fail_api("旧密码错误")
    user.set_password(res_json.get("newPassword"))
    db.session.add(user)
    db.session.commit()
    return success_api("更改成功")


@user_index.put('/self/updateInfo')
@user_login_required(log=False)
def update_info():
    req_json = request.json
    r = User.query.filter_by(id=g.client_user.id).update(
        {"realname": req_json.get("realName"), "remark": req_json.get("details")})
    db.session.commit()
    if not r:
        return fail_api(msg="出错啦")
    return success_api(msg="更新成功")


@user_index.route('/yibanLogin', methods=['POST', 'GET'])
def yiban_login():
    if request.method == 'GET':
        return render_template('User/yiban_login.html')
    else:
        return fail_api(msg="该功能仍在维护中")


@user_index.route('/eduLogin', methods=['POST'])
def edu_login():
    return fail_api(msg="该功能维护中")
